#!/bin/bash

set -e
pushd $(cd $(dirname ${0})/..; pwd) > /dev/null

bold() {
    echo "$(tty -s && tput bold)$1$(tty -s && tput sgr0)" 
}

clean() {
    bold "paddle clean"
    rm -rf "./third_party/src/paddle"
}

sync() {
    bold "paddle sync"
    [ -d "./third_party/src/paddle" ] || git clone --quiet --recursive https://github.com/PaddlePaddle/Paddle.git "./third_party/src/paddle"
    pushd "./third_party/src/paddle" > /dev/null
    git pull --quiet --prune
    git submodule sync --quiet
    git submodule update --quiet --init --recursive
    popd > /dev/null
}

schema() {
    bold "paddle schema"
    [[ $(grep -U $'\x0D' ./src/paddle-proto.js) ]] && crlf=1
    npx pbjs -t static-module -w closure --no-encode --no-delimited --no-comments --no-convert --no-verify --no-create --keep-case -r paddle -o ./src/paddle-proto.js ./third_party/src/paddle/paddle/fluid/framework/framework.proto
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./src/paddle-proto.js ./src/paddle-proto.js
    fi
}

while [ "$#" != 0 ]; do
    command="$1" && shift
    case "${command}" in
        "clean") clean;;
        "sync") sync;;
        "schema") schema;;
    esac
done
